package com.arcsoft.commonbase.utils

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.widget.FrameLayout

class KeyboardStateObserver(activity: Activity) {
    companion object {
        fun getKeyboardStateObserver(activity: Activity): KeyboardStateObserver {
            return KeyboardStateObserver(activity)
        }
    }

    private var mChildOfContent: View? = null
    private var usableHeightPrevious = -1
    private var listener:OnKeyboardVisibilityListener? = null

    init {
        val content = activity.findViewById<FrameLayout>(android.R.id.content)
        mChildOfContent = content.getChildAt(0)
        mChildOfContent?.viewTreeObserver?.addOnGlobalLayoutListener {
            possiblyResizeChildOfContent()
        }
    }

    fun setOnKeyboardVisibilityListener(listener: OnKeyboardVisibilityListener) {
        this.listener = listener
    }

    private fun possiblyResizeChildOfContent() {
        val usableHeightNow = computeUsableHeight()
        if(usableHeightNow != usableHeightPrevious) {
            val usableHeightSankeyboard = mChildOfContent?.rootView?.height?:0
            val heightDiff = usableHeightSankeyboard - usableHeightNow
            if (heightDiff > (usableHeightSankeyboard / 4)) {
                listener?.onKeyboardShow()
            } else {
                listener?.onKeyboardHide()
            }
            usableHeightPrevious = usableHeightNow
        }
    }

    private fun computeUsableHeight():Int {
        val r = Rect()
        mChildOfContent?.getWindowVisibleDisplayFrame(r)
        return r.bottom - r.top
    }

    interface OnKeyboardVisibilityListener {
        fun onKeyboardShow()
        fun onKeyboardHide()
    }
}